package com.project.action;

import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import sun.misc.BASE64Decoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.*;
import jxl.write.*;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import java.util.*;

public class SingleAccountExportServlet extends HttpServlet {
	
	static private String baseAccount = "";
	static private String baseBank = "";
	static private String baseName = "";
	static private String baseId = "";
	static private String baseTel = "";
	static private String baseOrigo = "";
	static private String baseCurrentAddress = "";
	static private String baseIdAddress = "";
	static private String baseJob = "";
	static private String inFundCount = "";
	static private String outFundCount = "";
	static private String inFundMoney = "";
	static private String outFundMoney = "";
	static private String accountCount = "";
	static private String accountNumCount = "";
	static private String directAccount = "";
	static private String directName = "";
	static private String directId = "";
	static private String directMode = "";
	static private String curveUrl = "";
	static private int resultType = -1;
	static private int statisType = -1;
	static public String fileName = "";
	static private String sortTableTitle = "";
	static private String sortFirstColTitle = "";
	static private String sortSecondColTitle = "";
	static private List<String> sortResultList = null;

	/**
	 * Constructor of the object.
	 */
	public SingleAccountExportServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		request.setCharacterEncoding("UTF-8");
		fileName = request.getParameter("fileName");
		String baseInfo = request.getParameter("expBaseInfo");
		String resultInfo = request.getParameter("expResultInfo");
		fileName += ".xls";
		//fileName = "C:\\temp\\downloadStore\\"+fileName;
		
		String returnMsg = "success";
		String[] baseInfos = baseInfo.split("@@");
		
		if (baseInfos.length != 9)
		{
			return;
		}
		
		baseAccount = baseInfos[0];
		baseBank = baseInfos[1];
		baseName = baseInfos[2];
		baseId = baseInfos[3];
		baseTel = baseInfos[4];
		baseOrigo = baseInfos[5];
		baseCurrentAddress = baseInfos[6];
		baseIdAddress = baseInfos[7];
		baseJob = baseInfos[8];
		if (resultInfo.equals(""))
		{
			ResponseMessage(returnMsg, response);
			return;
		}
		String[] resultInfos = resultInfo.split(",,");
		if (resultInfos.length != 2)
		{
			returnMsg = "分析结果获取错误";
			ResponseMessage(returnMsg, response);
			return;
		}
		String resultTypeStr = resultInfos[0];
		String resultData = resultInfos[1];
		
		
		
		if (resultTypeStr.equals("0"))
		{
			resultType = 0;
			String[] statisInfos = resultData.split("@,");
			if (statisInfos.length != 2 && statisInfos.length != 3)
			{
				returnMsg = "分析结果获取错误-获取是否为直接账户信息错误";
				ResponseMessage(returnMsg, response);
				return;
			}
			String statisTypeStr = statisInfos[0];
			
			if (statisTypeStr.equals("0"))
			{
				statisType = 0;
				if (statisInfos.length != 2)
				{
					returnMsg = "分析结果获取错误-获取是否为直接账户信息类型匹配错误";
					ResponseMessage(returnMsg, response);
					return;
				}
				String statisData = statisInfos[1];
				String []statisDatas = statisData.split("@@");
				
				if (statisDatas.length != 6)
				{
					returnMsg = "分析结果获取错误-获取统计交易结果错误";
					ResponseMessage(returnMsg, response);
					return;
				}
				
				inFundCount = statisDatas[0];
				outFundCount = statisDatas[1];
				inFundMoney = statisDatas[2];
				outFundMoney = statisDatas[3];
				accountCount = statisDatas[4];
				accountNumCount = statisDatas[5];
			}
			else
			{
				statisType = 1;
				if (statisInfos.length != 3)
				{
					returnMsg = "分析结果获取错误-获取是否为直接账户信息类型匹配错误";
					ResponseMessage(returnMsg, response);
					return;
				}
				
				String []statisDirectInfos = statisInfos[1].split("@@");
				if (statisDirectInfos.length != 4)
				{
					returnMsg = "分析结果获取错误-获取直接账户数据结果错误";
					ResponseMessage(returnMsg, response);
					return;
				}
				
				directAccount = statisDirectInfos[0];
				directName = statisDirectInfos[1];
				directId = statisDirectInfos[2];
				directMode = statisDirectInfos[3];
				
				String statisData = statisInfos[2];
				String []statisDatas = statisData.split("@@");
				
				if (statisDatas.length != 6)
				{
					returnMsg = "分析结果获取错误-获取统计交易结果错误";
					ResponseMessage(returnMsg, response);
					return;
				}
				
				inFundCount = statisDatas[0];
				outFundCount = statisDatas[1];
				inFundMoney = statisDatas[2];
				outFundMoney = statisDatas[3];
				accountCount = statisDatas[4];
				accountNumCount = statisDatas[5];
			}
		}
		else if (resultTypeStr.equals("1") || resultTypeStr == "1")
		{
			resultType = 1;
			String []sortInfos = resultData.split("@@");
			
			if (sortInfos.length != 4)
			{
				returnMsg = "排序结果获取错误";
				ResponseMessage(returnMsg, response);
				return;
			}
			
			sortTableTitle = sortInfos[0];
			sortFirstColTitle = sortInfos[1];
			sortSecondColTitle = sortInfos[2];
			
			String sortDataStr = sortInfos[3];
			
			String []sortDatas = sortDataStr.split("@,");
			sortResultList = new ArrayList<String>();
			for (int i = 0; i < sortDatas.length; ++i)
			{
				String sortResult = sortDatas[i];
				String []sortResults = sortResult.split(",@");
				
				if (sortResults.length != 2)
				{
					returnMsg = "排序结果获取错误-排序结果个数错误";
					ResponseMessage(returnMsg, response);
					return;
				}

				sortResultList.add(sortResult);
			}
		}
		else if (resultTypeStr.equals("2") || resultTypeStr == "2")
		{
			resultType = 2;
			curveUrl = resultData;
			String filePath = "C:\\temp\\downloadStore\\image\\";
			BASE64Decoder decoder = new BASE64Decoder();
			try {
				byte[] bytes1 = decoder.decodeBuffer(curveUrl);
				ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
				BufferedImage image = ImageIO.read(bais);
				if (image != null)
				{
					ImageIO.write(image, "png", new File(filePath , "curve.png"));
				}
			} 
			catch (IOException e) {
				e.printStackTrace();
				returnMsg = "曲线图解析错误";
				ResponseMessage(returnMsg, response);
				return;
			}
		}
		else
		{
			returnMsg = "未知类型";
			ResponseMessage(returnMsg, response);
			return;
		}
		

		ResponseMessage(returnMsg, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	private void ResponseMessage(String msg, HttpServletResponse response)
	throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println(msg);
		out.flush();
		out.close();
	}
	
	public static void writeExcel(OutputStream os) throws Exception {
		try
		{
			WritableWorkbook workbook = Workbook.createWorkbook(os);
			WritableSheet sheet = workbook.createSheet("单账户统计分析结果", 0);
			
			WritableFont titleFont = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD);
			WritableFont labelFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
			WritableFont contentFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD);
			WritableCellFormat titleFormat = new WritableCellFormat(titleFont);
			WritableCellFormat labelFormat = new WritableCellFormat(labelFont);
			WritableCellFormat contentFormat = new WritableCellFormat(contentFont);
			
			Label title = null;
			Label label = null;
			Label content = null;
			
			//base information part --begin
			title = new Label(0, 0, "账户基本信息", titleFormat);
			sheet.addCell(title);
			
			label = new Label(0, 1, "银行账号", labelFormat);
			sheet.addCell(label);
			
			label = new Label(1, 1, "开户银行", labelFormat);
			sheet.addCell(label);
			
			label = new Label(2, 1, "账户名", labelFormat);
			sheet.addCell(label);
			
			label = new Label(3, 1, "身份证", labelFormat);
			sheet.addCell(label);
			
			label = new Label(4, 1, "联系电话", labelFormat);
			sheet.addCell(label);
			
			label = new Label(5, 1, "籍贯", labelFormat);
			sheet.addCell(label);
			
			label = new Label(6, 1, "职业", labelFormat);
			sheet.addCell(label);
			
			label = new Label(7, 1, "现常驻住址", labelFormat);
			sheet.addCell(label);
			
			label = new Label(8, 1, "身份证住址", labelFormat);
			sheet.addCell(label);
			
			content = new Label(0, 2, baseAccount, contentFormat);
			sheet.addCell(content);
			
			content = new Label(1, 2, baseBank, contentFormat);
			sheet.addCell(content);
			
			content = new Label(2, 2, baseName, contentFormat);
			sheet.addCell(content);
			
			content = new Label(3, 2, baseId, contentFormat);
			sheet.addCell(content);
			
			content = new Label(4, 2, baseTel, contentFormat);
			sheet.addCell(content);
			
			content = new Label(5, 2, baseOrigo, contentFormat);
			sheet.addCell(content);
			
			content = new Label(6, 2, baseJob, contentFormat);
			sheet.addCell(content);
			
			content = new Label(7, 2, baseCurrentAddress, contentFormat);
			sheet.addCell(content);
			
			content = new Label(8, 2, baseIdAddress, contentFormat);
			sheet.addCell(content);
			//base information part --end
			
			//result information part -- begin
			if (resultType == 0)
			{//statistics information part
				if (statisType == 0)
				{
					title = new Label(0, 4, "统计结果", titleFormat);
					sheet.addCell(title);
					
					label = new Label(0, 5, "资金流进笔数", labelFormat);
					sheet.addCell(label);
					
					label = new Label(1, 5, "资金流出笔数", labelFormat);
					sheet.addCell(label);
					
					label = new Label(2, 5, "资金流进总额", labelFormat);
					sheet.addCell(label);
					
					label = new Label(3, 5, "资金流出总额", labelFormat);
					sheet.addCell(label);
					
					label = new Label(4, 5, "涉及账户数", labelFormat);
					sheet.addCell(label);
					
					label = new Label(5, 5, "涉及账号数", labelFormat);
					sheet.addCell(label);
					
					content = new Label(0, 6, inFundCount, contentFormat);
					sheet.addCell(content);
					
					content = new Label(1, 6, outFundCount, contentFormat);
					sheet.addCell(content);
					
					content = new Label(2, 6, inFundMoney, contentFormat);
					sheet.addCell(content);
					
					content = new Label(3, 6, outFundMoney, contentFormat);
					sheet.addCell(content);
					
					content = new Label(4, 6, accountCount, contentFormat);
					sheet.addCell(content);
					
					content = new Label(5, 6, accountNumCount, contentFormat);
					sheet.addCell(content);
				}
				else
				{
					title = new Label(0, 4, "选取的直接账户信息", titleFormat);
					sheet.addCell(title);
					
					label = new Label(0, 5, "银行账号", labelFormat);
					sheet.addCell(label);
					
					label = new Label(1, 5, "账户名", labelFormat);
					sheet.addCell(label);
					
					label = new Label(2, 5, "身份证", labelFormat);
					sheet.addCell(label);
					
					label = new Label(3, 5, "交易类型", labelFormat);
					sheet.addCell(label);
					
					content = new Label(0, 6, directAccount, contentFormat);
					sheet.addCell(content);
					
					content = new Label(1, 6, directName, contentFormat);
					sheet.addCell(content);
					
					content = new Label(2, 6, directId, contentFormat);
					sheet.addCell(content);
					
					content = new Label(3, 6, directMode, contentFormat);
					sheet.addCell(content);
					
					title = new Label(0, 8, "统计结果", titleFormat);
					sheet.addCell(title);
					
					label = new Label(0, 9, "资金流进笔数", labelFormat);
					sheet.addCell(label);
					
					label = new Label(1, 9, "资金流出笔数", labelFormat);
					sheet.addCell(label);
					
					label = new Label(2, 9, "资金流进总额", labelFormat);
					sheet.addCell(label);
					
					label = new Label(3, 9, "资金流出总额", labelFormat);
					sheet.addCell(label);
					
					label = new Label(4, 9, "涉及账户数", labelFormat);
					sheet.addCell(label);
					
					label = new Label(5, 9, "涉及账号数", labelFormat);
					sheet.addCell(label);
					
					content = new Label(0, 10, inFundCount, contentFormat);
					sheet.addCell(content);
					
					content = new Label(1, 10, outFundCount, contentFormat);
					sheet.addCell(content);
					
					content = new Label(2, 10, inFundMoney, contentFormat);
					sheet.addCell(content);
					
					content = new Label(3, 10, outFundMoney, contentFormat);
					sheet.addCell(content);
					
					content = new Label(4, 10, accountCount, contentFormat);
					sheet.addCell(content);
					
					content = new Label(5, 10, accountNumCount, contentFormat);
					sheet.addCell(content);
				}
			}
			else if (resultType == 1)
			{
				title = new Label(0, 4, sortTableTitle, titleFormat);
				sheet.addCell(title);
				
				label = new Label(0, 5, sortFirstColTitle, labelFormat);
				sheet.addCell(label);
				
				label = new Label(1, 5, sortSecondColTitle, labelFormat);
				sheet.addCell(label);
				
				Iterator<String> iter = sortResultList.iterator();
				int row = 6;
				String item = "";
				while(iter.hasNext())
				{
					item = (String)iter.next();
					String []results = item.split(",@");
					if (results.length != 2)
					{
						continue;
					}
					
					content = new Label(0, row, results[0], contentFormat);
					sheet.addCell(content);
					
					content = new Label(1, row, results[1], contentFormat);
					sheet.addCell(content);
					++row;
				}
			}
			else if (resultType == 2)
			{
				title = new Label(0, 4, "曲线图", titleFormat);
				sheet.addCell(title);
				WritableImage image = new WritableImage(1, 6,
						15, 40,
						new File("C:\\temp\\downloadStore\\image\\curve.png"));
				sheet.addImage(image);
			}
			

			workbook.write();
			workbook.close();
		}
		catch(Exception e)
		{
			 e.printStackTrace();
		}
	}
}
